//
//  STDiscountsViewController.m
//  TMGold
//
//  Created by Mac on 2017/12/11.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "STDiscountsViewController.h"
#import "TMGDiscountsTableViewCell.h"
#import "TMGExchangeViewController.h"
#import "TMGDiscountModel.h"
@interface STDiscountsViewController ()
@property(nonatomic, strong) NSMutableArray<TMGDiscountModel*>                     *dataSouce;
@end

@implementation STDiscountsViewController
- (instancetype)initWithType:(TMGDiscountType)type{
    if (self == [super init]) {
        self.type = type;
    }
    return self;
}

#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    NSString * title;
    if (self.type == TMGDiscountTypeHongbao) {
        title = @"黄金券";
    }else{
       title = @"优惠券";
    }
    self.title = title;
    self.tableView.st_noreslutView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, 100, UIScreenWidth, 400) title:[NSString stringWithFormat:@"暂无%@",title] buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendListRequest];
    }];
    [self.tableView.mj_header beginRefreshing];


    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    if (self.type != TMGDiscountTypeHongbao) {
         [self st_setRightItemWithTitle:@"兑换码"  titleColor:[UIColor whiteColor]];
 //   }
   
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [TMGDiscountsTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    TMGDiscountsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[TMGDiscountsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    __weak typeof(self) weakSelf =  self;
    TMGDiscountModel * model = self.dataSouce[indexPath.row];
    cell.model = model;

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    [formatter setTimeZone:GTMzone];
    NSDate * date = [formatter dateFromString:model.end];
    NSInteger num = [date timeIntervalSince1970];
    NSInteger now = [[NSDate st_localCurrentDate] timeIntervalSince1970];
    if (num >= now && !model.is_used.boolValue) {
        [cell.useButton setTitle:@"立即领取" forState:UIControlStateNormal];
        [cell.useButton setTitleColor:TM_orangeColor forState:UIControlStateNormal] ;
        cell.useButton.userInteractionEnabled = YES;
        if (self.type == TMGDiscountTypeHongbao) {
            cell.useButton.hidden = YES;
        }else{
            cell.useButton.hidden = NO;
            
        }

    }else{
        cell.useButton.hidden = NO;
        [cell.useButton setTitle:@"已失效" forState:UIControlStateNormal];
        if (model.is_used.boolValue) {
           [cell.useButton setTitle:@"已使用" forState:UIControlStateNormal];
        }
        [cell.useButton setTitleColor:ThirdTextColor forState:UIControlStateNormal] ;
        cell.useButton.userInteractionEnabled = NO;
    }
    [cell.useButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedUseButtonWithIndexPath:indexPath];
    }];
    
    if ([model.title containsString:@"加息"]) {
        NSString * rate = [NSString stringWithFormat:@"%ld%@",@(model.number.floatValue * 100).integerValue,@"%"];
        cell.titleLable.text = [NSString stringWithFormat:@"%@(加息%@,%@元可以使用)",cell.titleLable.text,rate,model.more];
    }
    //判断是否是优惠券中 的新手，新手优惠券不现实立即领取
    
    if ([model.title containsString:@"新手"]) {
      cell.titleLable.text = [NSString stringWithFormat:@"%@(%@元代金券)",cell.titleLable.text,
                              model.number];
    }
    if (!cell.useButton.hidden) {
        if ([model.title containsString:@"新手"]) {
            cell.useButton.hidden = YES;
        }else{
            cell.useButton.hidden =  cell.useButton.hidden;
        }
    }

    
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TMGDiscountModel * model = self.dataSouce[indexPath.row];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)st_rightBarAction:(id)sender{
    [self.navigationController pushViewController:[[TMGExchangeViewController alloc] initWithType:self.type] animated:YES];
}
- (void)onSelectedUseButtonWithIndexPath:(NSIndexPath*)indexPath{
    TMGDiscountModel * model = self.dataSouce[indexPath.row];
    [self sendUseRequestWithID:model.discountID.description];
}
#pragma mark --NetWork Method
- (void)sendListRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    [dic setObject:@"0" forKey:@"g_type"];

    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/getUsefulCouple"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSArray * array = responseObject[@"data"];
                                                 self.dataSouce = [NSMutableArray new];
                                                 for (NSDictionary *modelDic in array) {
                                                     TMGDiscountModel * model = [TMGDiscountModel mj_objectWithKeyValues:modelDic];
                                                     if (self.type == TMGDiscountTypeHongbao) {
                                                         //加息
                                                         if ([model.type isEqualToString:@"1"]  ) {
                                                              [self.dataSouce addObject:model];
                                                         }
                                                     }else{
                                                         //优惠
                                                         if ([model.type isEqualToString:@"2"]||[model.type isEqualToString:@"3"]) {
                                                             [self.dataSouce addObject:model];
                                                         }
                                                     }
                                                    
                                                 }
                                                 [self.tableView reloadData];
                                                 [self.tableView.mj_header endRefreshing];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 [self.tableView.mj_header endRefreshing];
                                             }];
}
- (void)sendUseRequestWithID:(NSString*)ID{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (ID.length) {
        [dic setObject:ID forKey:@"cid"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/gold_couple"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"领取成功"];
                                                 [self.tableView.mj_header beginRefreshing];

                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];

                                             }];
}
@end
